# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymongo
from spider.settings import mongo_host, mongo_port, mongo_db_name


class SpiderPipeline:
    client = None
    db = None

    def __init__(self):
        self.client = pymongo.MongoClient(host=mongo_host, port=int(mongo_port))
        self.db = self.client[mongo_db_name]

    def process_item(self, item, spider):
        data = dict(item)
        collection = self.db['pianshen']
        article = collection.find_one({'article_id': data['article_id']})
        if article:
            collection.update({'article_id': data['article_id']}, data)
        else:
            collection.insert_one(data)
        return item
